<?php defined('SYSPATH') OR die('No direct access allowed.');

class ProblemController {
    private static $rendererpath;

    private static function imgsrc_replace1($matches)
    {
        $rendererpath = self::$rendererpath;
        $r = str_replace($matches[1], '', $matches[0]);
        $p = str_replace('files/', $rendererpath.'?file=', $matches[1]);
        $r .= $p;
        return $r;
    }

    private static function imgsrc_replace2($matches)
    {
        $rendererpath = self::$rendererpath;
        $r = str_replace($matches[1], '', $matches[0]);
        $p = str_replace($rendererpath.'?file=', 'files/' , $matches[1]);
        $r .= $p;
        return $r;
    }

    public static function show_description (Problem_Model $problem, $rendererpath, $tostring = TRUE)
    {
        self::$rendererpath = $rendererpath;
        $contents = file_get_contents($problem->description_path);
        $pattern = "/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\'\ >]*)/";
        $contents = preg_replace_callback($pattern, 'ProblemController::imgsrc_replace1', $contents);
        if ($tostring)
        {
            return $contents;
        }
        else
        {
            echo $contents;
            exit;
        }
    }

    public static function show_submission(Submission_Model $submission)
    {
        $submission_view_path = $submission->problem->get_view_directory_path()."/submission.php";
        include $submission_view_path;
    }

    public static function submit_submission(Submission_Model $submission)
    {
        $controller_file = $submission->problem->get_view_directory_path()."/controller.php";
        include $controller_file;
        return call_user_func('submit', $submission);
    }

    public function render_view($problemid, $view)
    {

    }

    public static function render_view_file($problem, $filename)
    {
        $filepath = $problem->view_files_path . $filename;
        if (file_exists($filepath))
        {
            header('Content-Type: '.file::mime($filepath));
            header('Content-Length: '.filesize($filepath));
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            readfile($filepath);
            exit;
        }
        else
        {
            return false;
        }
    }

    public static function show_submit(Problem_Model $problem)
    {
        $submit_view_path = $problem->get_view_directory_path()."/submit.php";
        include $submit_view_path;
    }
}